﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using TorchlightModOverseer.Domain;

namespace TorchlightModOverseer.Infrastructure
{
	public class StorageService : IStorageService
	{
		public StorageService() : this(new DefaultSerializationService()) { }

		public StorageService(ISerializerService serializer)
		{
			Serializer = serializer;
		}

		public ISerializerService Serializer { get; set; }

		public void Store<T>(T value)
		{
			Store(null, value);
		}

		public void Store<T>(string name, T value)
		{
			var path = CreateStoragePath<T>(name);
			using (var writer = new StreamWriter(path))
			{
				Serializer.Serialize(writer, value);
			}
		}

		public T Retrieve<T>()
		{
			return Retrieve<T>(null);
		}

		public T Retrieve<T>(string name)
		{
			var path = CreateStoragePath<T>(name);
			if (File.Exists(path))
			{
				using (var reader = new StreamReader(path))
				{
					return Serializer.Deserialize<T>(reader);
				}
			}
			else
			{
				return default(T);
			}
		}

		private string CreateStoragePath<T>(string nameQualifier)
		{
			var path = Path.Combine(Environment.CurrentDirectory, "Data\\");
			if(!Directory.Exists(path))
			{
				Directory.CreateDirectory(path);
			}

			var filePath = Path.Combine(path, string.IsNullOrWhiteSpace(nameQualifier) ? typeof(T).FullName : nameQualifier)
									+ typeof(T).Name + Serializer.FileExtension;

			return filePath;
		}
	}
}
